package io.potato.ts.common;

import io.potato.core.AppException;
import io.potato.core.util.Hashs;
import io.potato.ts.service.WebSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 短信验证码
 */
@Component
public class SmsCaptcha {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private WebSmsService webSmsService;

    private static final String CACHE_PREFIX = "sms_captcha:";

    private static final String HAS_CACHE_PREFIX = "has_sms_captcha:";

    /**
     * 发送验证码
     * @param userCode
     * @param mobile
     */
    public void sendCaptcha(String userCode, String mobile) {

        String hasKey = HAS_CACHE_PREFIX + userCode;
        if (redisTemplate.opsForValue().get(hasKey) == null) {
            // 要间隔60秒才可以重新发送验证码

            // 生成6位随机验证码
            String code = Hashs.randomDigit(6);

            // 发送验证码到手机
            webSmsService.submitSms(userCode, mobile, "您正在修改系统的登录密码，验证码是：" + code);

            // 保存验证码到redis
            redisTemplate.opsForValue().set(getKey(mobile), code, 15, TimeUnit.MINUTES);

            // 标记已经发送过验证码
            redisTemplate.opsForValue().set(hasKey, "1", 60, TimeUnit.SECONDS);
        } else {
            throw new AppException("请不要频繁发送验证码");
        }
    }

    /**
     * 检查验证码是否正确
     * @param mobile
     * @param code
     * @return
     */
    public boolean check(String mobile, String code) {
        String key = getKey(mobile);
        String serverCode = redisTemplate.opsForValue().get(key);
        if (serverCode == null) {
            // 没有此验证码
            return false;
        }

        if (serverCode.equals(code)) {
            // 验证完要删掉，验证码失效
            try {
                redisTemplate.delete(key);
            } catch (Exception e) {

            }
            return true;
        } else {
            // 验证码不正确
            return false;
        }
    }

    private String getKey(String mobile) {
        return CACHE_PREFIX + mobile;
    }
}
